package com.yuyu.shop.infrastructure.persistence.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yuyu.shop.domain.order.DO.OrderDO;
import com.yuyu.shop.domain.order.repository.OrderRepository;
import com.yuyu.shop.infrastructure.persistence.convert.OrderPoConvert;
import com.yuyu.shop.infrastructure.persistence.mapper.OrderMapper;
import com.yuyu.shop.infrastructure.persistence.po.OrderPO;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @author
 * @version 1.0
 * @description: order实现类
 * @date 2022/8/3 10:56
 */
@Service
@RequiredArgsConstructor(onConstructor = @_(@Autowired))//不需要加注解注入
public class OrderRepositoryImpl implements OrderRepository {

    private final OrderMapper orderMapper;

    @Override
    public OrderDO getById(Long id) {
        OrderPO orderPO = orderMapper.selectById(id);
        return OrderPoConvert.PO2DO(orderPO);
    }

    @Override
    public OrderDO getByOrderId(String orderId) {
        LambdaQueryWrapper<OrderPO> wrapper=new LambdaQueryWrapper<>();
        wrapper.eq(OrderPO::getOrderId,orderId);
        OrderPO orderPO = orderMapper.selectOne(wrapper);
        return OrderPoConvert.PO2DO(orderPO);
    }

    @Override
    public Page<OrderDO> getByUserId(Long userId, Integer type, Long current, Long pageSize) {
        Page<OrderPO> orderByUserId = orderMapper.getOrderByUserId(new Page<>(current, pageSize), userId, type);
        IPage<OrderDO> orderDOIPage = new Page<OrderDO>().setRecords(orderByUserId.getRecords().stream().map(OrderPoConvert::PO2DO).collect(Collectors.toList()))
                .setTotal(orderByUserId.getTotal()).setPages(orderByUserId.getPages()).setSize(orderByUserId.getSize()).setCurrent(orderByUserId.getCurrent());
        return (Page<OrderDO>) orderDOIPage;
    }


    @Override
    public Boolean updateById(OrderDO orderDO) {
        OrderPO orderPO = OrderPoConvert.DO2PO(orderDO);
        int insert = orderMapper.updateById(orderPO);
        return insert>0 ?Boolean.TRUE:Boolean.FALSE;
    }

    @Override
    public Boolean delete(String orderId) {
        return null;
    }

    @Override
    public Boolean insert(OrderDO orderDO) {
        OrderPO orderPO = OrderPoConvert.DO2PO(orderDO);
        OrderPO orderPO1 = orderMapper.selectOne(new LambdaQueryWrapper<OrderPO>().eq(OrderPO::getOrderId, orderDO.getOrderId()));
        if (Objects.nonNull(orderPO1)){
            return Boolean.FALSE;
        }
        int insert = orderMapper.insert(orderPO);
        return insert>0 ?Boolean.TRUE:Boolean.FALSE;
    }
}
